package com.flyme.module.base.provider.service.impl;

import com.flyme.common.core.utils.ObjectUtils;
import com.flyme.core.base.supper.service.impl.BaseServiceImpl;
import com.flyme.core.base.utils.RedisUtils;
import com.flyme.module.base.client.entity.SysDict;
import com.flyme.module.base.client.entity.SysDictData;
import com.flyme.module.base.provider.mapper.SysDictMapper;
import com.flyme.module.base.provider.service.SysDictDataService;
import com.flyme.module.base.provider.service.SysDictService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 字典接口实现
 * @author flyme
 */
@Slf4j
@Service
public class SysDictServiceImpl extends BaseServiceImpl<SysDictMapper,SysDict> implements SysDictService{
    
    @Autowired
    private SysDictDataService dictDataService;
    @Autowired
    private RedisUtils redisUtils;
    @Override
    public List<SysDict> selectAll(){
        return list(q().orderByAsc("sortOrder"));
    }

    @Override
    public SysDict findByType(String type){

        List<SysDict> list=list(q().eq("dicType",type));
        if(list!=null&&list.size()>0){
            return list.get(0);
        }
        return null;
    }

    @Override
    public List<SysDict> search(String key){
        return list(q().like("dicTitle",key).or().like("dicType",key));
    }
    
    @Override
    public void initDictRedis() {
        List<String> dictKeys = new ArrayList<>();
        Map<String, Object> dictDataMaps = new HashMap<>(0);
        List<SysDict> dicts = list();
        if (ObjectUtils.isNotEmpty(dicts)) {
            redisUtils.del("DICT_KEYS");
            dicts.forEach(dict -> {
                String dictType = dict.getDicType();
                dictKeys.add(dictType);
                redisUtils.setList("DICT_KEYS", dictType);
                List<SysDictData> dictDataList = dictDataService.findByDictId(dict.getId());
                if (ObjectUtils.isNotEmpty(dictDataList)) {
                    dictDataList.forEach(dictdata -> {
                        String value = dictdata.getDicDataValue();
                        dictDataMaps.put(dictType + "_" + value, dictdata.getDicDataTitle());
                    });
                }
            });
            redisUtils.del("DICTDATA_MAPS");
            redisUtils.setMap("DICTDATA_MAPS", dictDataMaps);
            System.out.println("##############初始化字典####################" + dictKeys.size());
        }
    }

    /**
     * 根据code查询
     */
    public List<Map<String, Object>> selectByCode(String dicType){
        SysDict dict = getOne(q().eq(true, "dicType", dicType), false);
        List<Map<String, Object>> list = dictDataService.selectByPar(dict.getId());
        return list;
    }
}